package xonmp.notepaddemo;

import xonmp.notepaddemo.database.NotepadDbAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NoteEdit extends Activity {
	private EditText mTitleText;
	private EditText mBodyText;
	private Long mRowId;
	private NotepadDbAdapter mDbAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		mDbAdapter = new NotepadDbAdapter(this);
		mDbAdapter.open();
		
		setContentView(R.layout.note_edit);
		setTitle(R.string.edit_note);
		
		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		
		Button confirmButton = (Button) findViewById(R.id.confirm);
		
		mRowId = (savedInstanceState == null) ? null :
			(Long) savedInstanceState.getSerializable(NotepadDbAdapter.KEY_ROWID);
		if (mRowId == null)
		{
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(NotepadDbAdapter.KEY_ROWID) : null;
		}
		
		populateFields();
		
		confirmButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				setResult(RESULT_OK);
				finish();
			}
		});
	}
	
	private void populateFields()
	{
		if (mRowId != null)
		{
			Cursor note = mDbAdapter.fetchNote(mRowId);
			startManagingCursor(note);
			mTitleText.setText(note.getString(
					note.getColumnIndexOrThrow(NotepadDbAdapter.KEY_TITLE)));
			mBodyText.setText(note.getString(
					note.getColumnIndexOrThrow(NotepadDbAdapter.KEY_BODY)));
		}		
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(NotepadDbAdapter.KEY_ROWID, mRowId);
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		saveState();
		mDbAdapter.close();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		populateFields();
	}
	
	private void saveState()
	{
		String title = mTitleText.getText().toString();
		String body = mBodyText.getText().toString();
		
		if (mRowId == null)
		{
			long id = mDbAdapter.createNote(title, body);
			if (id > 0)
			{
				mRowId = id;
			}
		} else {
			mDbAdapter.updateNote(mRowId, title, body);
		}
	}
}
